package threadLock.lock.AQS;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;

/**
 * 使用自定义锁实现一个消费模型
 */
public class ConsumptionModel {
    //自定义锁
    private final static AQSTest lock = new AQSTest();
    private final static Condition notFull = lock.newCondition();
    private final static Condition notEmpty = lock.newCondition();
    //阻塞队列
    private final static Queue<String> queue = new LinkedBlockingQueue<>();
    private final static Integer maxSize = 10;

    public static void main(String[] args) {
        //当前线程是生产者  如果生产者满了等待 没有满 添加元素并通知所有
        Thread producers = new Thread(() -> {
            lock.lock();
            try {
                while (queue.size() == maxSize){
                    notEmpty.await();
                }
                queue.add("ele");
                notFull.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "producers");

        Thread consumers = new Thread(() -> {
            lock.lock();
            try {
                while (queue.size() == 0){
                    notFull.await();
                }
                System.out.println(queue.poll());
                notEmpty.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "consumers");

        producers.start();
        consumers.start();
    }
}
